package gw.com.android.ui.news;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Locale;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.TopNewsRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.utils.PackStatis;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.view.XRecyclerView;

/**
 * 要闻Fragment
 *
 * @author jett
 * @since 2017-11-23.
 */
public class TopNewsFragment extends PushMsgTabFragment {

    private TextView tvTips;
    private LinearLayout llEmpty;
    private TopNewsAdapter mAdapter;
    private TopNewsRequest topNewsRequest = new TopNewsRequest();
    private Runnable animTask;
    private XRecyclerView mRcvContent;

    @Override
    public int getLayoutId() {
        return R.layout.view_home_topnews;
    }

    @Override
    protected void initLayoutView() {
        tvTips = mRootView.findViewById(R.id.topnews_tips);
        llEmpty = mRootView.findViewById(R.id.topnews_empty);
        mRcvContent = mRootView.findViewById(R.id.topnews_list);
        mRcvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRcvContent.setPullRefreshEnabled(false);
        final List<String> marks = GTConfig.instance().getTopNewsMark();
        mAdapter = new TopNewsAdapter((BaseActivity) getActivity(), marks);
        //mRcvContent.setAdapter(mAdapter);
        mRcvContent.setAdapter(new EmptyAdapter());
        mRcvContent.hideFooter();
        mRcvContent.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getNewsData();
            }

            @Override
            public void onLoadMore() {
                nextPage();
            }
        });
        mAdapter.setOnItemClickListener(new TopNewsAdapter.OnItemClickListener() {
            @Override
            public void OnItemClicked(RecyclerView.Adapter adapter, View view, int position) {
                TopNewsRequest.TopNewsData item = mAdapter.getItem(position);
                if (item != null) {
                    PackStatis.getToService("clickFnews", "Fnews", null, null);
                    if (!mAdapter.marked(item.id)) {
                        if (position < 20) {
                            GTConfig.instance().addTopNewsMark(item.id);
                        }
                        mAdapter.addMark(item.id);

                        //这里要等到 服务器时间取到之后，再执行刷新，要考虑线程差异
                    }

                    // 阅读数，要求点击一次之后立即展示新的阅读量；
                    //int pviews = Integer.parseInt(TextUtils.isEmpty(item.pviews) ? "0" : item.pviews);
                    //item.pviews = String.valueOf(pviews + 1);
                    mAdapter.notifyItemChanged(position, item);//所以设定局部更新
                    mAdapter.notifyDataSetChanged();

                    //H5的方式展示详情
                    String url = ConfigUtil.instance().getUrlPath("topNewsDetailH5") + item.id + ".html";
                    DataItemDetail detail = new DataItemDetail();
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, url);
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, getString(R.string.home_trade_news_topnews));
                    ActivityManager.showWebPageActivity(getActivity(), detail, null);
                }
            }
        });
    }

    @Override
    protected void initViewData() {
        List<TopNewsRequest.TopNewsData> list = topNewsRequest.fetchLocal();
        if (list != null && !list.isEmpty()) {
            refreshUi(list);
        }
        mRcvContent.setRefreshing(true);
    }

    private void refreshUi(List<TopNewsRequest.TopNewsData> list) {
        if (mAdapter == null) {
            return;
        }
        if (list != null && !list.isEmpty()) {
            mAdapter.updateData(list);
        }
        int itemCount = mAdapter.getItemCount();
        if (itemCount <= 0) {
            llEmpty.setVisibility(View.VISIBLE);
            mRcvContent.setVisibility(View.GONE);
        } else {
            llEmpty.setVisibility(View.GONE);
            mRcvContent.setVisibility(View.VISIBLE);
            mRcvContent.setNoMore(!topNewsRequest.hasNextPage());
        }
    }

    private void appendUi(List<TopNewsRequest.TopNewsData> list) {
        if (mAdapter == null || list == null || list.isEmpty()) {
            return;
        }
        mAdapter.appendData(list);
    }

    private void showTips(List<TopNewsRequest.TopNewsData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<String> ids = mAdapter.getNewsIds();
        if (ids == null || ids.isEmpty()) {
            showTips(list.size());
            return;
        }
        int count = 0;
        for (TopNewsRequest.TopNewsData data : list) {
            if (!ids.contains(data.id)) {
                count++;
            }
        }
        if (count > 0) {
            showTips(count);
        }
    }

    private void getNewsData() {
        /*topNewsRequest.call(new ReqCallBack<List<TopNewsRequest.TopNewsData>>() {
            @Override
            public void onReqSuccess(List<TopNewsRequest.TopNewsData> result) {
                mRcvContent.refreshComplete();
                showTips(result);
                refreshUi(result);
                mRcvContent.setPullRefreshEnabled(false);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mRcvContent.refreshComplete();
                refreshUi(null);
                mRcvContent.setPullRefreshEnabled(false);
            }
        });*/
    }

    private void nextPage() {
        /*topNewsRequest.nextPage(new ReqCallBack<List<TopNewsRequest.TopNewsData>>() {
            @Override
            public void onReqSuccess(List<TopNewsRequest.TopNewsData> result) {
                mRcvContent.loadMoreComplete();
                mRcvContent.setNoMore(!topNewsRequest.hasNextPage());
                appendUi(result);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mRcvContent.loadMoreComplete();
            }
        });*/
    }

    private void showTips(int count) {
        String text = String.format(Locale.getDefault(), getString(R.string.home_trade_news_update_count), count);
        tvTips.setText(text);
        tvTips.setVisibility(View.VISIBLE);
        tvTips.clearAnimation();
        if (animTask != null) {
            AppMain.getApp().getHandler().removeCallbacks(animTask);
            animTask = null;
        }
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        AlphaAnimation alphaAnim = new AlphaAnimation(0, 1);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                hideTipsDelay();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        tvTips.startAnimation(animSet);
    }

    private void hideTipsDelay() {
        animTask = new Runnable() {
            @Override
            public void run() {
                hideTips();
            }
        };
        AppMain.getApp().getHandler().postDelayed(animTask, 800);
    }

    private void hideTips() {
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        AlphaAnimation alphaAnim = new AlphaAnimation(1, 0);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tvTips.setVisibility(View.GONE);
                animTask = null;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        animSet.setFillAfter(true);
        tvTips.startAnimation(animSet);
    }

    @Override
    public void onRefresh() {
        mRcvContent.setPullRefreshEnabled(true);
        mRcvContent.smoothScrollToPosition(0);
        mRcvContent.setRefreshing(true);
        getNewsData();
    }

    private class EmptyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_topnews_stub, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return 5;
        }

    }

}
